package com.gitee.wsl.platform.thread


import com.gitee.wsl.concurrent.executor.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import java.util.logging.Logger
import kotlin.concurrent.withLock

/** A [com.gitee.wsl.platform.concurrent.runner.WorkRunner] implementation that is backed by an [ExecutorService]. */
 class ExecutorServiceWorkRunner(private val service: ExecutorService) : Executor {

    private val logger = Logger.getLogger("ExecutorServiceWorkRunner")
    private val lock = ReentrantLock()

    override val isDisposed: Boolean
        get() = service.isShutdown

    override fun exec(runnable: Runnable) {
        lock.withLock {
            if (!service.isTerminated && !service.isShutdown) {
                service.submit(runnable)
            }
        }
    }

    override fun dispose() {
        try {
            lock.withLock {
                val runnables = service.shutdownNow()

                if (runnables.isNotEmpty()) {
                    logger.warning ("Disposing ExecutorServiceWorkRunner with ${runnables.size} outstanding tasks.")
                }
            }

            if (!service.awaitTermination(100, TimeUnit.MILLISECONDS)) {
                logger.warning("ExecutorService shutdown timed out; there are still tasks executing")
            }
        } catch (e: InterruptedException) {
            logger.warning( "Timeout when disposing work runner")
        }
    }

}
